package netty.demo03;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import netty.demo02.TestEventLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * EventLoopServer
 *
 * @author chenxin
 * @date 2022/05/26 18:23
 **/
public class EventLoopServer {

    private static final Logger log = LoggerFactory.getLogger(TestEventLoop.class);

    public static void main(String[] args) {

        // 细分2 自定义EventLoopGroup 可以将耗时可能比较长的逻辑交给他执行 让这个逻辑不影响Nio的读写handler
        DefaultEventLoopGroup defaultEventLoopGroup = new DefaultEventLoopGroup();

        new ServerBootstrap()
                // 细分 第一个参数为boss  第二个为worker(这里给worker分配两个线程)
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast("nio",new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.info("byteBuf:{}", byteBuf.toString(Charset.defaultCharset()));

                                // 将事件传递到下一个handler
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(defaultEventLoopGroup,"default",new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.info("default byteBuf:{}", byteBuf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                }).bind(8080);

    }

}